package com.PQLoad
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class Load extends Sprite
	{
		protected var urlload:URLLoader;
		protected var load:Loader;
		protected var url:String;
		protected var _byteLoaded:int=0;
		protected var _byteTotal:int=0;
		protected var onOpen:Function;
		protected var onComplete:Function;
		protected var onProgress:Function;
		protected var onError:Function;
		protected var _type:int=-1;
		public function Load(_url:String,param:Object=null)	{
			url=_url;
			this.name=url;
			if(param&&param.onOpen)onOpen=param.onOpen;
			if(param&&param.onProgress)onProgress=param.onProgress;
			if(param&&param.onError)onError=param.onError;
			if(param&&param.onComplete)onComplete=param.onComplete;
			urlload=new URLLoader();
			urlload.addEventListener(Event.OPEN,loadOpen);
			urlload.addEventListener(ProgressEvent.PROGRESS,loading);
			urlload.addEventListener(Event.COMPLETE,loaded);
			urlload.addEventListener(IOErrorEvent.IO_ERROR,loadError);
			trace("addLoad:"+_url);
		}
		/**中断当前的加载**/
		public function stop():void{
			try{
				if(urlload)urlload.close();
				if(load)load.close();
			}catch(err){}
			destroy();
		}
		protected function loadOpen(e:Event):void{
			_byteTotal=urlload.bytesTotal;
			if(onOpen)onOpen();
		}
		protected function loading(e:ProgressEvent):void{
			_byteLoaded=e.bytesLoaded;
			if(onProgress)onProgress(e);
		}
		protected function loaded(e:Event):void{
			removeListen();
			if(onComplete)	onComplete();
			removeFunc();
		}
		protected function loadError(e:IOErrorEvent):void{
			trace("loadError:"+url);
			if(onError)onError.apply(null,[e]);
			destroy();
		}
		protected function removeListen():void{
			if(!urlload)return;
			urlload.removeEventListener(Event.OPEN,loadOpen);
			urlload.removeEventListener(ProgressEvent.PROGRESS,loading);
			urlload.removeEventListener(Event.COMPLETE,loaded); 
			urlload.removeEventListener(IOErrorEvent.IO_ERROR,loadError);
			urlload=null;
		}
		/**销毁**/
		protected function destroy():void{
			removeListen();
			removeFunc();
			url=null;
			load=null;
			_byteLoaded=0;
			_byteTotal=0;
		}
		protected function removeFunc():void{
			onComplete=null;
			onError=null;
			onProgress=null;
			onOpen=null;
		}
		public function get byteTotal():int{
			return _byteTotal;
		}
		public function get byteLoaded():int{
			return _byteLoaded;
		}
		/**所加载的资源类型-1:未知,0:图片,1:SWF,2:文本/XML,3:zip**/
		public function get type():int{
			return _type;
		}
		public function set type(value:int):void{
			_type=value;
		}
	}
}